// pages/SCM/store/goodsApplyStockUp/goodsApplyStockUp.js
const app = getApp()
const util = require('../../../../utils/util.js')
const lbbService = require('../../../service/service.js')

Page({

  data: {
    id: '',
    goodsList: [],
    uindex: 0,
    goodsApply: {},
    hideFlag: true,
    imgArray: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
      this.goodsApplyItem();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    let that = this
    that.toast = that.selectComponent("#toast")
    this.personalModal = this.selectComponent("#personalModal")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  inputLogisticsNum: function(e) {
    let logisticsNum = e.detail.value;
    this.setData({
      logisticsNum: logisticsNum
    })
  },
  //扫码获取物流编号
  scanQrCode: function() {
    let that = this
    wx.scanCode({
      success(res) {
        that.setData({
          logisticsNum: res.result
        });
      }
    })
  },
  getWarehouseAndThirdParty: function() {
    let that = this
    lbbService.getWarehouseAndThirdParty({}, function(res) {
      let warehouseAndThirdPartys = res.data;
      let addwarehouse = {
        id: -1,
        name: '添加类型',
        thirdFlag: '1'
      };
      warehouseAndThirdPartys.push(addwarehouse);
      that.setData({
        warehouseAndThirdPartys: warehouseAndThirdPartys,
        warehouseAndThirdPartyId: warehouseAndThirdPartys[0].id,
        warehouseAndThirdPartyName: warehouseAndThirdPartys[0].name,
        thirdFlag: warehouseAndThirdPartys[0].thirdFlag,
      })
      that.getGoodsStockUp(warehouseAndThirdPartys[0]);
    })
  },
  chooseWarehouseAndThirdParty: function(e) {
    let that = this
    let item = e.currentTarget.dataset.item;
    that.setData({
      warehouseAndThirdPartyId: item.id,
      warehouseAndThirdPartyName: item.name,
      thirdFlag: item.thirdFlag,
    });
    that.getGoodsStockUp(item);
  },

  getGoodsStockUp: function (warehouse){
    let that=this;
    let goodsList = that.data.goodsList;
    if (warehouse.thirdFlag){//第三方不需要查询库存
      for (var j in goodsList) {
        let g = goodsList[j];
        g.stockNum = undefined;
        g.addNum='';
      }
      that.setData({ goodsList: goodsList });
      return false;
    }
    //获取仓库能提供满足需求的最大物品数量
    let goodsDetails = [];
    goodsList.forEach(item => {
      let goodsDetail = {};
      goodsDetail.goodsId = item.goodsStatId;
      goodsDetail.goodsNum = item.goodsNum;
      goodsDetails.push(goodsDetail);
    });
    let params = {
      warehouseId: warehouse.id
    };
    params.detailJsonStr = JSON.stringify(goodsDetails);
    lbbService.getGoodsStockUp(params, function (res) {
      let arr = res.data;
      for (var i in goodsList) {
        let g = goodsList[i];
        g.addNum = '';
        g.stockNum = 0;//可能仓库没这个物品
        for (var j in arr) {
          if (arr[j].goodsId == g.goodsStatId) {
            g.stockNum = arr[j].goodsNum;
          }
        }
        
      }
      that.setData({ goodsList: goodsList });
    })
  },

  thirdNameInp: function(e) {
    let thirdName = e.detail.value;
    this.setData({
      thirdName: thirdName
    })
  },
  //限制输入两位小数
  logisticsPriceInp: function(e) {
    let num = e.detail.value;
    num = num.toString(); //先转换成字符串类型
    if (num.indexOf('.') == 0) { //第一位就是 .
      num = '0' + num
    }
    num = num.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
    num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    if (num.indexOf(".") < 0 && num != "") {
      num = parseFloat(num);
    }
    this.setData({
      logisticsPrice: num
    })
  },
  inputName: function (e) {
    console.log('e====', e)
    let inputName = e.detail.value;
    let addNum = parseInt(inputName);
    let item = this.data.goodsList[e.currentTarget.dataset.index];
    let lessNum=item.goodsNum-item.deliverNum;
    if (addNum > item.stockNum) {
      wx.showToast({
        title: '请小于库存数',
        image: '/images/gantan.png'
      })
      item.addNum = '';
    }else if(addNum>lessNum){
      wx.showToast({
        title: '请小于待发货数',
        image: '/images/gantan.png'
      })
      item.addNum = lessNum;
    } else {
      item.addNum = addNum;
    }
    this.setData({ goodsList: this.data.goodsList });

  },
  showModel: function() {
    this.setData({
      hideFlag: false
    })
  },

  hideModel: function() {
    this.setData({
      hideFlag: true
    })
  },
  addImg: function(e) {
    let that = this;
    wx.chooseImage({
      count: 6,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          that.data.imgArray.push(res.tempFilePaths[i])
        }
        that.setData({
          imgArray: that.data.imgArray
        })
        console.log(that.data.imgArray)
      }
    })
  },
  deleteImg: function(e) {
    let that = this
    let deleteIndex = e.currentTarget.dataset.index
    that.data.imgArray.splice(deleteIndex, 1)
    that.setData({
      imgArray: that.data.imgArray
    })
  },





  goodsApplyItem: function() {
    let that = this;
    let goodsList = [];
    lbbService.goodsApplyItem({
      id: this.data.id
    }, function(res) {
      res.data.goodsAccessDetails.forEach(item => {
        let selectGoods = {};
        selectGoods.goodsId = item.goods.id;
        selectGoods.goodsName = item.goods.name;
        selectGoods.goodsStatId = item.goodsId;
        selectGoods.goodsNum = item.goodsNum;
        // selectGoods.addNum = 1;
        selectGoods.deliverNum = item.deliverNum;
        // console.log('selectGoods-->',selectGoods);
        goodsList.push(selectGoods);
      });
      // console.log('goodsList-->',goodsList);
      that.setData({
        goodsApply: res.data,
        goodsList: goodsList,
      });
      that.getWarehouseAndThirdParty();
    });
  },

 

  //表单提交前确认
  formSubmit: function(e) {
    let that = this
    console.log(e)
    let formData = e.detail.value
    let goodsList = this.data.goodsList;
    let goodsDetails = [];
    let stockComplete=1;
    goodsList.forEach(item => {
      if(item.addNum){
        let goodsDetail = {};
        goodsDetail.goodsId = item.goodsStatId;
        goodsDetail.goodsNum = item.addNum;
        goodsDetails.push(goodsDetail);
      }
      let lessNum=item.goodsNum-item.deliverNum;
      let addNum = item.addNum ? item.addNum:0;
      if (addNum<lessNum){
        stockComplete=''
      }
    });
   
    if (goodsDetails.length==0) {
      wx.showToast({
        title: '至少发一种物品',
        image: '/images/gantan.png'
      })
      return false;
    }
    formData.accessDetailsStr = JSON.stringify(goodsDetails);
    formData.upType = that.data.thirdFlag?'2':'1';
    formData.warehouseId = that.data.warehouseAndThirdPartyId;
    formData.stockComplete = stockComplete;
    
    that.setData({
      formData: formData
    });
    let modalText = '确定提交发货吗？'
    that.personalModal.showModal(modalText, that.uploadImg)
  },
  uploadImg: function() {
    let that = this
    let imgArray = that.data.imgArray
    wx.showLoading({
      title: '正在上传图片',
    })
    util.upLoadImg(app.globalData.header, imgArray, 0, [], that.submitStockUp)
  },

  submitStockUp: function (imgIdArray) {
    let that = this
    let formData = that.data.formData;
    wx.hideLoading()
    let imgIds = imgIdArray.join();
    if (imgIds) {
      formData.imgIds = imgIds;
    } 
    lbbService.goodsApplyDeliveryPackage(formData, function(res) {
      wx.showToast({
        title: '发货成功',
      })
      setTimeout(function() {
        wx.navigateBack({
          delta: 1
        })
      }, 1500)
    })

  },




})